package com.dabai.applicationmanager.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
import android.graphics.drawable.Icon;
import android.os.Build;
import android.os.Environment;

import androidx.appcompat.app.AlertDialog;

import com.dabai.applicationmanager.R;
import com.dabai.applicationmanager.bean.AppBaseInfo;
import com.dabai.applicationmanager.bean.AppScanBaseInfo;
import com.dabai.applicationmanager.dialog.MdcDialog;
import com.dabai.applicationmanager.dialog.TipAlertDialog;
import com.dabai.applicationmanager.impl.OnCompleteListener;
import com.dabai.applicationmanager.shizuku.Shell;
import com.dabai.applicationmanager.shizuku.ShizukuShell;
import com.dabai.dbutils.toast.DBToast;
import com.dabai.dbutils.utils.AppUtils;
import com.dabai.dbutils.utils.DabaiUtils;
import com.dabai.dbutils.utils.FileUtils;
import com.dabai.dbutils.utils.SharedPreferencesBasicUse;
import com.dabai.dbutils.utils.ShellUtils;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;

import java.io.File;
import java.util.ArrayList;

/**
 * Description : Other
 *
 * @author BAI
 */
public class OtherUtils {


    @SuppressLint("UnspecifiedImmutableFlag")
    public static void addShortCut(Context context, String name, int icon, Intent intent) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            ShortcutManager shortcutManager = (ShortcutManager) context.getSystemService(Context.SHORTCUT_SERVICE);
            if (shortcutManager.isRequestPinShortcutSupported()) {
                intent.setAction(Intent.ACTION_VIEW); //action必须设置，不然报错
                ShortcutInfo info;
                info = new ShortcutInfo.Builder(
                        context,
                        "The only id" + (int) (Math.random() * 10000)
                )
                        .setIcon(Icon.createWithResource(context, icon))
                        .setShortLabel(name)
                        .setIntent(intent)
                        .build();

                //当添加快捷方式的确认弹框弹出来时，将被回调
                PendingIntent shortcutCallbackIntent =
                        PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

                shortcutManager.requestPinShortcut(info, shortcutCallbackIntent.getIntentSender());
            }
        }else {
            DabaiUtils.showToast(context,"当前系统不支持快捷方式!");
        }
    }


    public static AlertDialog showDialog(Context context, String text) {
        return new MaterialAlertDialogBuilder(context, R.style.DBTheme_Dialog_RoundTheme)
                .setTitle("提示")
                .setMessage(text)
                .setPositiveButton("确认", null)
                .show();
    }


    /**
     * 安装的apk
     *
     * @param activity           活动
     * @param scanBaseInfos      扫描基础信息
     * @param onCompleteListener 在完整的侦听器
     */
    public static void installApks(Activity activity, ArrayList<AppScanBaseInfo> scanBaseInfos, OnCompleteListener onCompleteListener) {

        MdcDialog.showConfirmDialog(activity,
                "提示",
                scanBaseInfos.size() <= 1 ? "确定安装 " + scanBaseInfos.get(0).getName() + " 嘛?" : "确定安装共 " + scanBaseInfos.size() + " 个软件包嘛?"
                , new MdcDialog.OnConfirmDialogButtonListener() {
                    @Override
                    public void confirm() {
                        onCompleteListener.start();
                        TipAlertDialog.getInstance(activity).showTipLayout("正在批量安装...");

                        new Thread(() -> {
                            for (int i = 0; i < scanBaseInfos.size(); i++) {

                                String path = scanBaseInfos.get(i).getPath();

                                switch (OtherUtils.getImplementWay(activity)) {
                                    case 1:

                                        if (!AppUtils.isSystemApplication(activity, activity.getPackageName())) {

                                            AppUtils.installApk(activity, new File(path));

                                        } else {
                                            String shellCommand = " pm install -r " + path;
                                            ShellUtils.execCommand(shellCommand, false);
                                        }

                                        break;
                                    case 2:
                                        ShellUtils.installApk(path);
                                        break;
                                    case 3:
                                        ShizukuShell.getInstance().exec(new Shell.Command("pm", "install -r ", path));
                                        break;
                                }

                                int finalI = i;
                                activity.runOnUiThread(() -> {
                                    TipAlertDialog.getInstance(activity).showTipLayout("正在安装 " + scanBaseInfos.get(finalI).getName() + "\n总进度:" + (int) (((float) finalI / (float) scanBaseInfos.size()) * 100) + "%");
                                    onCompleteListener.progress((int) (((float) finalI / (float) scanBaseInfos.size()) * 100));
                                });
                            }
                            activity.runOnUiThread(() -> {
                                TipAlertDialog.getInstance(activity).hideTipLayout();
                                DBToast.showText(activity, "安装完成!", true);
                                onCompleteListener.complete();
                            });
                        }).start();

                    }

                    @Override
                    public void cancel() {
                    }
                }).getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

    }


    /**
     * 卸载的apk
     * 卸载批量的 apk
     *
     * @param appBaseInflows     应用基础流入
     * @param activity           活动
     * @param onCompleteListener 在完整的侦听器
     */
    public static void uninstallApks(Activity activity, ArrayList<AppBaseInfo> appBaseInflows, OnCompleteListener onCompleteListener) {

        com.dabai.applicationmanager.dialog.MdcDialog.showConfirmDialog(activity,
                "提示",
                appBaseInflows.size() <= 1 ? "确定卸载 " + appBaseInflows.get(0).getName() + " 嘛?" : "确定卸载共 " + appBaseInflows.size() + " 个程序嘛?"
                , new MdcDialog.OnConfirmDialogButtonListener() {
                    @Override
                    public void confirm() {
                        onCompleteListener.start();
                        TipAlertDialog.getInstance(activity).showTipLayout("正在批量卸载...");

                        new Thread(() -> {
                            for (int i = 0; i < appBaseInflows.size(); i++) {

                                String packageName = appBaseInflows.get(i).getPackageName();

                                switch (OtherUtils.getImplementWay(activity)) {
                                    case 1:

                                        if (!AppUtils.isSystemApplication(activity, activity.getPackageName())) {
                                            AppUtils.uninstallApk(activity, packageName);

                                        } else {
                                            String shellCommand = " pm uninstall " + packageName;
                                            ShellUtils.execCommand(shellCommand, false);
                                        }

                                        break;
                                    case 2:
                                        ShellUtils.uninstallApk(packageName);
                                        break;
                                    case 3:
                                        ShizukuShell.getInstance().exec(new Shell.Command(
                                                "pm uninstall ", packageName));

                                        break;
                                }

                                int finalI = i;
                                activity.runOnUiThread(() -> {
                                    TipAlertDialog.getInstance(activity).showTipLayout("正在卸载 " + appBaseInflows.get(finalI).getName() + "\n总进度:" + (int) (((float) finalI / (float) appBaseInflows.size()) * 100) + "%");
                                    onCompleteListener.progress((int) (((float) finalI / (float) appBaseInflows.size()) * 100));
                                });
                            }
                            activity.runOnUiThread(() -> {
                                TipAlertDialog.getInstance(activity).hideTipLayout();
                                //  DBToast.showText(activity,"卸载完成!",true);
                                onCompleteListener.complete();
                            });
                        }).start();

                    }

                    @Override
                    public void cancel() {
                    }
                }).getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

    }


    /**
     * 得到执行的方式
     *
     * @param context 上下文
     * @return int
     */
    public static int getImplementWay(Context context) {
        switch (OtherUtils.getSettingSharedPreferences(context).getString("implement_way"
                , "normal")) {
            case "normal":
                return 1;
            case "root":
                return 2;
            case "shizuku":
                return 3;
        }
        return 0;
    }

    /**
     * 得到排序的方式
     *
     * @param context 上下文
     * @return int
     */
    public static int getSortWay(Context context) {
        switch (OtherUtils.getSettingSharedPreferences(context).getString("sorting_way"
                , "time")) {
            case "name":
                return 1;
            case "time":
                return 2;
            case "size":
                return 3;
            case "api":
                return 4;
        }
        return 2;
    }


    /**
     * 得到设置默认的 配置表
     *
     * @param context 上下文
     * @return {@link SharedPreferences}
     */
    public static SharedPreferences getSettingSharedPreferences(Context context) {
        return context.getSharedPreferences(context.getPackageName() + "_preferences", 0);
    }


    /**
     * 获得提取目录
     *
     * @return {@link File}
     */
    public static File getExportDirectory(Context context) {
        SharedPreferencesBasicUse.init(context);
        String defDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "AppExtract").getAbsolutePath();
        String dir = SharedPreferencesBasicUse.getString("extractDir", defDir);
        return FileUtils.getDir(new File(dir));
    }

    /**
     * 获得接收文件目录
     *
     * @param context 上下文
     * @return {@link File}
     */
    public static File getReceiveFileDirectory(Context context) {
        SharedPreferencesBasicUse.init(context);
        String defDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "AppExtract").getAbsolutePath();
        String dir = SharedPreferencesBasicUse.getString("extractDir", defDir);
        return FileUtils.getDir(new File(new File(dir).getParentFile(), "AppReceive"));
    }

    /**
     * 得到tmp目录
     *
     * @param context 上下文
     * @return {@link File}
     */
    public static File getTmpDirectory(Context context) {
        return FileUtils.getDir(context.getExternalCacheDir());
    }


}
